package top.buaarobot.webserver.web.rest;

import com.alibaba.fastjson.JSONObject;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import top.buaarobot.webserver.domain.CollectionInfo;
import top.buaarobot.webserver.repository.CollectionRepository;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/collection")
public class CollectionResource {

    private final CollectionRepository collectionRepository;

    public CollectionResource(CollectionRepository collectionRepository) {
        this.collectionRepository = collectionRepository;
    }

    @GetMapping(value = "/get/{name}")
    public ResponseEntity<CollectionInfo> getCollectionByName(@PathVariable("name") String name){
       List<CollectionInfo> collectionInfoList = this.collectionRepository.findByName(name);
       if(collectionInfoList.size() > 0){
           return ResponseEntity.ok().body(collectionInfoList.get(0));

       }
       else{
           CollectionInfo newCollection = new CollectionInfo();
           newCollection.setName(name);
           String content = "[{\"id\":0,\"label\": \"" + name + "\",\"expandedIcon\":\"pi pi-folder-open\",\"collapsedIcon\":\"pi pi-folder\",\"children\":[],\"expanded\":true}]";
           newCollection.setContent(content);
           newCollection = this.collectionRepository.save(newCollection);
           return ResponseEntity.ok().body(newCollection);
       }

    }

    @PostMapping(value = "/update")
    public ResponseEntity<CollectionInfo> updateCollectionByName(@RequestBody JSONObject json){
        System.out.println(json);
        CollectionInfo response = new CollectionInfo();
        Long id = Long.parseLong(json.getString("id"));
        Optional<CollectionInfo> collectionInfoOptional = this.collectionRepository.findById(id);
        if(collectionInfoOptional.isPresent()){
            CollectionInfo collectionInfo = collectionInfoOptional.get();
            //collectionInfo.setId(Long.parseLong(json.getString("id")));
            collectionInfo.setContent(json.getString("content"));
            response = this.collectionRepository.save(collectionInfo);
        }
        return ResponseEntity.ok().body(response);
    }
}
